import java.util.Date;
import java.util.Iterator;
import java.util.List;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.hslf.record.CurrentUserAtom;

import edu.bds.PSPDataExcelImporter;
import edu.bds.PSPDataExcelReader;

class UploadController{
	
	def authenticateService
	
	User currentUser = new User()
	def index = {
		def authPrincipal = authenticateService.principal()
		currentUser = User.findByUsername(authPrincipal.username)
		List taskList = new ArrayList()
		for(projectTeam in currentUser.projectTeams){			
			for(task in projectTeam.project.tasks){				
				taskList.add (task)
			}
		}
		session.taskList = taskList
	}
	
	static final int BUFF_SIZE = 1024;
	static final byte[] buffer = new byte[BUFF_SIZE];
	static final String outputFolder = "web-app/psplogdata/";
	
	def upload = {		
		def file = request.getFile("pspLogFile");
		def authPrincipal = authenticateService.principal()
		currentUser = User.findByUsername(authPrincipal.username)
		Task selectedTask = Task.findById(params.taskId)
		if(file && !file.empty) {
			InputStream inputStream = file.getInputStream();
			OutputStream outputStream = new FileOutputStream(outputFolder + "${file.getOriginalFilename()}")
			while(true){
				synchronized (buffer) {
					int amtRead = inputStream.read (buffer);
					if (amtRead == -1) {
						break;
					}
					outputStream.write (buffer, 0, amtRead);
				}
			}
			inputStream.close();
			outputStream.close();
		}
		String fileName = grailsAttributes.getApplicationContext().getResource("psplogdata/${file.getOriginalFilename()}").getFile().toString();
		
		
		//		PSPDataExcelImporter pspDataExcelImporter = new PSPDataExcelImporter(fileName);
		//		
		//		pspDataExcelImporter.setConfig (PSPDataExcelReader.getSheetName (fileName, 0));
		//		
		//		def pspDataMapList = pspDataExcelImporter.getPSPData();
		//		
		//		println pspDataMapList;
		//		
		//		pspDataMapList.each { Map pspDatum -> 
		//			def newPspDatum = new PspData(pspDatum)			
		//			newPspData.subTask = SubTask.findById(1)
		//			newPspData.user = User.findById(1)
		//			
		//			if(!newPspDatum.save(flush: true)){
		//				flash.message = "Data not saved, errors = ${newPspDatum.errors}"
		//			}
		//			else {
		//				flash.message = "Data saved successfully!!!"
		//			}
		//		}
		
		PSPDataExcelReader pspDataExcelReader = new PSPDataExcelReader();
		pspDataExcelReader.readXls (fileName);
		List<List<String>> timeLogData = pspDataExcelReader.getTimeLogData();
		
		Iterator<List<String>> itr = timeLogData.iterator();
		
		def prevData = []
		//prevData = PspData.findByUserAndTask(currentUser,selectedTask)
		prevData = PspData.findAllByUser(currentUser)
		for(pD in prevData){
			if(pD.task.id == selectedTask.id){	
				pD.delete()
			}
		}
		def newPspData = []
		while (itr.hasNext()) {
			List<String> rowVal = itr.next();
			Iterator<String> rowValItr = rowVal.iterator();
			def newPD = new PspData();
			while (rowValItr.hasNext()) {
				newPD.phaseName = rowValItr.next();
				newPD.startDate = new Date(Date.parse(rowValItr.next()));
				String actualTime = rowValItr.next()
				newPD.actualTimeInMin = Integer.valueOf(actualTime.substring(0, actualTime.lastIndexOf("."))).intValue();
				String interruptTime = rowValItr.next()
				newPD.interuptTimeInMin = Integer.valueOf(interruptTime.substring(0, interruptTime.lastIndexOf("."))).intValue();
			}
			newPD.task = selectedTask
			newPD.user = currentUser
			newPspData << newPD
		}
		newPspData*.save(flush:true)
		
		List pspDataList = new ArrayList()
		prevData = []
		//prevData = PspData.findByUserAndTask(currentUser,selectedTask)
		prevData = PspData.findAllByUser(currentUser)
		for(pD in prevData){
			if(pD.task.id == selectedTask.id){	
				pspDataList.add pD
			}
		}
		session.pspDataList = pspDataList
		//redirect(action: "index")
	}
}	